package com.kancy.stream.rabbit.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Objects;

/**
 * DynamicInterfaceBeanResolver
 *
 * @author kancy
 * @date 2020/3/8 11:26
 */
public class DynamicInterfaceBeanResolver implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    public <T> T getBean(String beanName, Class<T> interfaceClass){
        if (Objects.isNull(interfaceClass) || !interfaceClass.isInterface()){
            return null;
        }
        try {
            return applicationContext.getBean(String.format("%s%s", beanName, interfaceClass.getSimpleName()), interfaceClass);
        } catch (BeansException e) {
            return applicationContext.getBean(beanName, interfaceClass);
        }
    }

    public <T> T getBean(String beanName,String defBeanName, Class<T> interfaceClass){
        if (Objects.isNull(interfaceClass) || !interfaceClass.isInterface()){
            return null;
        }
        try {
            return applicationContext.getBean(String.format("%s%s", beanName, interfaceClass.getSimpleName()), interfaceClass);
        } catch (BeansException e) {
            try {
                return applicationContext.getBean(beanName, interfaceClass);
            } catch (BeansException ex) {
                return getBean(defBeanName, interfaceClass);
            }
        }
    }

    /**
     * Set the ApplicationContext that this object runs in.
     * Normally this call will be used to initialize the object.
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
}
